<?php
session_start();
include('../includes/config.php');
include('../includes/functions.php');

// 检查用户是否已登录，且是患者角色
if (!isset($_SESSION['user_id']) || $_SESSION['user_role'] != 'patient') {
    header("Location: ../login.php");
    exit();
}

// 获取患者ID
$patient_id = $_SESSION['user_id'];

// 获取患者信息
$stmt = $conn->prepare("SELECT * FROM users u JOIN patients p ON u.id = p.user_id WHERE u.id = ?");
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$patient_info = $stmt->get_result()->fetch_assoc();
$stmt->close();

// 处理表单提交
$feedback = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $department_id = $_POST['department_id'];
    $doctor_id = $_POST['doctor_id'];
    $appointment_date = $_POST['appointment_date'];
    $appointment_time = $_POST['appointment_time'];
    $reason = $_POST['reason'];
    
    // 验证输入
    if (empty($department_id) || empty($doctor_id) || empty($appointment_date) || empty($appointment_time)) {
        $feedback = '<div class="alert alert-danger">请填写所有必填字段</div>';
    } else {
        try {
            // 检查时间段是否已被预约
            $check_stmt = $conn->prepare("SELECT id FROM appointments WHERE doctor_id = ? AND appointment_date = ? AND appointment_time = ? AND status != 'cancelled'");
            $check_stmt->bind_param("iss", $doctor_id, $appointment_date, $appointment_time);
            $check_stmt->execute();
            $check_result = $check_stmt->get_result();
            
            if ($check_result->num_rows > 0) {
                $feedback = '<div class="alert alert-warning">该时间段已被预约，请选择其他时间</div>';
            } else {
                // 插入预约记录
                $status = 'pending'; // 初始状态为待确认
                $created_at = date('Y-m-d H:i:s');
                
                $insert_stmt = $conn->prepare("INSERT INTO appointments (patient_id, doctor_id, department_id, appointment_date, appointment_time, reason, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $insert_stmt->bind_param("iiisssss", $patient_info['id'], $doctor_id, $department_id, $appointment_date, $appointment_time, $reason, $status, $created_at);
                
                if ($insert_stmt->execute()) {
                    $feedback = '<div class="alert alert-success">预约成功提交，请等待医生确认</div>';
                    // 清空表单
                    $_POST = array();
                } else {
                    $feedback = '<div class="alert alert-danger">预约失败，请稍后重试：' . $insert_stmt->error . '</div>';
                }
                $insert_stmt->close();
            }
            $check_stmt->close();
        } catch (Exception $e) {
            $feedback = '<div class="alert alert-danger">发生错误：' . $e->getMessage() . '</div>';
        }
    }
}

// 获取科室列表
$departments = array();
$dept_stmt = $conn->prepare("SELECT * FROM departments ORDER BY name");
$dept_stmt->execute();
$dept_result = $dept_stmt->get_result();
while ($row = $dept_result->fetch_assoc()) {
    $departments[] = $row;
}
$dept_stmt->close();

// 如果URL中有科室参数，预选该科室
$selected_department = isset($_GET['department']) ? $_GET['department'] : '';

// 根据选择的科室获取医生列表
$doctors = array();
if (isset($_POST['department_id']) || $selected_department) {
    $dept_id = isset($_POST['department_id']) ? $_POST['department_id'] : $selected_department;
    $doc_stmt = $conn->prepare("SELECT d.*, u.name, u.email, u.phone 
                               FROM doctors d 
                               JOIN users u ON d.user_id = u.id 
                               WHERE d.department_id = ? 
                               ORDER BY u.name");
    $doc_stmt->bind_param("i", $dept_id);
    $doc_stmt->execute();
    $doc_result = $doc_stmt->get_result();
    while ($row = $doc_result->fetch_assoc()) {
        $doctors[] = $row;
    }
    $doc_stmt->close();
}

// 获取医生工作时间
function getDoctorSchedule($conn, $doctor_id, $date) {
    $schedule = array();
    
    // 获取医生正常工作时间
    $stmt = $conn->prepare("SELECT * FROM doctor_schedules WHERE doctor_id = ?");
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $result = $stmt->get_result();
    
    // 获取星期几 (0-周日, 1-周一, ..., 6-周六)
    $weekday = date('w', strtotime($date));
    
    while ($row = $result->fetch_assoc()) {
        // 检查当天是否是医生的工作日
        if ($row['weekday'] == $weekday) {
            // 工作时间段，假设是9:00-12:00, 14:00-17:00
            $morning_slots = array('09:00', '09:30', '10:00', '10:30', '11:00', '11:30');
            $afternoon_slots = array('14:00', '14:30', '15:00', '15:30', '16:00', '16:30');
            
            $available_slots = array_merge($morning_slots, $afternoon_slots);
            
            // 检查哪些时间段已经被预约
            $booked_stmt = $conn->prepare("SELECT appointment_time FROM appointments 
                                          WHERE doctor_id = ? AND appointment_date = ? 
                                          AND status != 'cancelled'");
            $booked_stmt->bind_param("is", $doctor_id, $date);
            $booked_stmt->execute();
            $booked_result = $booked_stmt->get_result();
            
            $booked_slots = array();
            while ($booked_row = $booked_result->fetch_assoc()) {
                $booked_slots[] = $booked_row['appointment_time'];
            }
            
            // 剔除已预约的时间段
            foreach ($available_slots as $slot) {
                if (!in_array($slot, $booked_slots)) {
                    $schedule[] = $slot;
                }
            }
            
            break;
        }
    }
    
    return $schedule;
}

// 默认选择今天的日期
$today = date('Y-m-d');
$min_date = $today;
$max_date = date('Y-m-d', strtotime('+30 days')); // 允许预约未来30天内

// 获取可选时间段
$available_times = array();
if (isset($_POST['doctor_id']) && isset($_POST['appointment_date'])) {
    $available_times = getDoctorSchedule($conn, $_POST['doctor_id'], $_POST['appointment_date']);
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>预约挂号 - 医院信息系统</title>
    <link rel="stylesheet" href="/assets\css/bootstrap_69c9e605.min.css">
    <link rel="stylesheet" href="/assets\css/style.css">
    <link rel="stylesheet" href="/assets\css/all_de197510.min.css">
</head>
<body>
    <div class="container-fluid">
        <div class="row">
            <!-- 侧边栏 -->
            <nav id="sidebar" class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
                <div class="position-sticky pt-3">
                    <div class="text-center mb-4">
                        <img src="../assets/images/patient-avatar.png" alt="患者头像" class="img-fluid rounded-circle mx-auto d-block" style="width: 80px;">
                        <h5 class="mt-2"><?php echo htmlspecialchars($patient_info['name']); ?></h5>
                        <p class="text-muted">患者ID: <?php echo htmlspecialchars($patient_info['id']); ?></p>
                    </div>
                    <ul class="nav flex-column">
                        <li class="nav-item">
                            <a class="nav-link" href="index.php">
                                <i class="fas fa-home"></i> 个人中心
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="appointments.php">
                                <i class="fas fa-calendar-check"></i> 我的预约
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link active" href="book_appointment.php">
                                <i class="fas fa-plus-circle"></i> 预约挂号
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="medical_records.php">
                                <i class="fas fa-notes-medical"></i> 病历记录
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="prescriptions.php">
                                <i class="fas fa-prescription"></i> 处方信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="bills.php">
                                <i class="fas fa-file-invoice-dollar"></i> 账单管理
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="profile.php">
                                <i class="fas fa-user"></i> 个人信息
                            </a>
                        </li>
                        <li class="nav-item">
                            <a class="nav-link" href="../logout.php">
                                <i class="fas fa-sign-out-alt"></i> 退出登录
                            </a>
                        </li>
                    </ul>
                </div>
            </nav>

            <!-- 主内容区 -->
            <main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
                <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
                    <h1 class="h2">预约挂号</h1>
                    <div class="btn-toolbar mb-2 mb-md-0">
                        <a href="appointments.php" class="btn btn-sm btn-outline-secondary">
                            <i class="fas fa-list"></i> 我的预约列表
                        </a>
                    </div>
                </div>

                <?php echo $feedback; ?>

                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">挂号信息</h5>
                    </div>
                    <div class="card-body">
                        <form method="post" id="appointmentForm">
                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="department_id" class="form-label">选择科室 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="department_id" name="department_id" required>
                                        <option value="">请选择科室</option>
                                        <?php foreach ($departments as $dept): ?>
                                            <option value="<?php echo $dept['id']; ?>" <?php if ((isset($_POST['department_id']) && $_POST['department_id'] == $dept['id']) || $selected_department == $dept['id']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($dept['name']); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                                <div class="col-md-6">
                                    <label for="doctor_id" class="form-label">选择医生 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="doctor_id" name="doctor_id" required <?php if (empty($doctors)) echo 'disabled'; ?>>
                                        <option value="">请先选择科室</option>
                                        <?php foreach ($doctors as $doc): ?>
                                            <option value="<?php echo $doc['id']; ?>" <?php if (isset($_POST['doctor_id']) && $_POST['doctor_id'] == $doc['id']) echo 'selected'; ?>>
                                                <?php echo htmlspecialchars($doc['name'] . ' (' . $doc['title'] . ')'); ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="row mb-3">
                                <div class="col-md-6">
                                    <label for="appointment_date" class="form-label">预约日期 <span class="text-danger">*</span></label>
                                    <input type="date" class="form-control" id="appointment_date" name="appointment_date" 
                                           min="<?php echo $min_date; ?>" max="<?php echo $max_date; ?>" 
                                           value="<?php echo isset($_POST['appointment_date']) ? $_POST['appointment_date'] : $today; ?>" required>
                                </div>
                                <div class="col-md-6">
                                    <label for="appointment_time" class="form-label">预约时间 <span class="text-danger">*</span></label>
                                    <select class="form-select" id="appointment_time" name="appointment_time" required <?php if (empty($available_times)) echo 'disabled'; ?>>
                                        <?php if (empty($available_times)): ?>
                                            <option value="">请先选择医生和日期</option>
                                        <?php else: ?>
                                            <option value="">请选择时间段</option>
                                            <?php foreach ($available_times as $time): ?>
                                                <option value="<?php echo $time; ?>" <?php if (isset($_POST['appointment_time']) && $_POST['appointment_time'] == $time) echo 'selected'; ?>>
                                                    <?php echo $time; ?>
                                                </option>
                                            <?php endforeach; ?>
                                        <?php endif; ?>
                                    </select>
                                </div>
                            </div>

                            <div class="mb-3">
                                <label for="reason" class="form-label">就诊原因</label>
                                <textarea class="form-control" id="reason" name="reason" rows="3" placeholder="请简要描述您的症状或就诊原因"><?php echo isset($_POST['reason']) ? htmlspecialchars($_POST['reason']) : ''; ?></textarea>
                            </div>

                            <div class="alert alert-info">
                                <h6><i class="fas fa-info-circle"></i> 挂号须知：</h6>
                                <ul class="mb-0">
                                    <li>请至少提前一天预约</li>
                                    <li>预约成功后，请在预约时间前15分钟到达医院</li>
                                    <li>如需取消预约，请提前24小时操作</li>
                                    <li>初诊患者请携带身份证等有效证件</li>
                                </ul>
                            </div>

                            <div class="text-center">
                                <button type="submit" class="btn btn-primary px-4">
                                    <i class="fas fa-calendar-check"></i> 提交预约
                                </button>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- 科室介绍 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="mb-0">科室介绍</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-heartbeat fa-3x text-danger mb-3"></i>
                                        <h5>内科</h5>
                                        <p class="text-muted">心脏病、高血压、糖尿病、消化系统疾病等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-cut fa-3x text-primary mb-3"></i>
                                        <h5>外科</h5>
                                        <p class="text-muted">骨科、普外科、神经外科、泌尿外科等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-female fa-3x text-info mb-3"></i>
                                        <h5>妇产科</h5>
                                        <p class="text-muted">妇科疾病、孕期检查、分娩、不孕不育等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-baby fa-3x text-success mb-3"></i>
                                        <h5>儿科</h5>
                                        <p class="text-muted">儿童疾病、生长发育、疫苗接种等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-eye fa-3x text-warning mb-3"></i>
                                        <h5>眼科</h5>
                                        <p class="text-muted">近视、白内障、青光眼、眼底疾病等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-tooth fa-3x text-info mb-3"></i>
                                        <h5>口腔科</h5>
                                        <p class="text-muted">牙齿保健、牙周疾病、口腔修复等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-brain fa-3x text-secondary mb-3"></i>
                                        <h5>神经内科</h5>
                                        <p class="text-muted">头痛、脑血管疾病、认知障碍等</p>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-3 mb-4">
                                <div class="card h-100">
                                    <div class="card-body text-center">
                                        <i class="fas fa-x-ray fa-3x text-dark mb-3"></i>
                                        <h5>影像科</h5>
                                        <p class="text-muted">X光、CT、核磁共振、超声等检查</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <!-- 脚本 -->
    <script src="/assets\js/jquery-3.6.0.min.js"></script></script></script>
    <script src="/assets\js/bootstrap.bundle.min.js"></script></script></script>
    <script>
        $(document).ready(function() {
            // 科室选择变化时，加载对应的医生
            $('#department_id').change(function() {
                var departmentId = $(this).val();
                if (departmentId) {
                    // 提交表单，重新加载页面以显示医生列表
                    $('#appointmentForm').submit();
                }
            });
            
            // 医生或日期变化时，加载可用时间段
            $('#doctor_id, #appointment_date').change(function() {
                var doctorId = $('#doctor_id').val();
                var appointmentDate = $('#appointment_date').val();
                
                if (doctorId && appointmentDate) {
                    // 提交表单，重新加载页面以显示可用时间
                    $('#appointmentForm').submit();
                }
            });
        });
    </script>
</body>
</html> 